<template>
  <div class="goods-recommendation">
    <!-- 个性化推荐标题 -->
    <div class="recommendation-header">
      <h3>
        <i class="el-icon-star-on" style="color: #E6A23C;"></i>
        基于您的信用分和偏好为您推荐
      </h3>
      <p>信用分：{{ userScore }}分，为您精选优质商品</p>
    </div>

    <!-- 推荐分类标签 -->
    <div class="recommendation-tags">
      <el-tag
        v-for="tag in recommendationTags"
        :key="tag.id"
        :type="activeTag === tag.id ? 'primary' : 'info'"
        @click="changeRecommendationTag(tag.id)"
        style="margin-right: 10px; cursor: pointer;">
        {{ tag.name }}
      </el-tag>
    </div>

    <!-- 推荐商品列表 -->
    <div class="recommendation-grid">
      <div v-for="item in filteredRecommendations" :key="item.goodsId" class="recommendation-card">
        <div class="item-badge" v-if="item.tags && item.tags.length > 0">
          <el-tag :type="getBadgeType(item.tags[0])" size="mini">{{ item.tags[0] }}</el-tag>
        </div>

        <div class="item-image">
          <img :src="getItemImage(item)" :alt="item.goodsName" @error="handleImageError" />
          <div class="item-score-badge">
            <span>{{ item.recommendScore }}分</span>
          </div>
        </div>

        <div class="item-info">
          <div class="item-title">{{ item.goodsName }}</div>
          <div class="item-description">{{ item.goodsDesc }}</div>

          <div class="item-features">
            <el-tag v-for="tag in item.tags" :key="tag" size="mini" style="margin-right: 5px;">
              {{ tag }}
            </el-tag>
          </div>

          <div class="item-price">
            <span class="current-price">¥{{ item.goodsPrice }}</span>
            <span class="discount" v-if="item.reason">信用专享</span>
          </div>

          <div class="item-rating">
            <span class="sales-count">推荐信用分：{{ item.recommendScore }}分</span>
          </div>
        </div>

<!--        <div class="item-actions">-->
<!--          <el-button-->
<!--            type="primary"-->
<!--            size="small"-->
<!--            @click="viewItemDetail(item)"-->
<!--            style="margin-right: 10px;">-->
<!--            查看详情-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            :type="canPurchase(item) ? 'success' : 'info'"-->
<!--            size="small"-->
<!--            @click="purchaseItem(item)"-->
<!--            :disabled="!canPurchase(item)">-->
<!--            {{ getPurchaseButtonText(item) }}-->
<!--          </el-button>-->
<!--        </div>-->
        <div class="item-actions">
          <el-button
            type="primary"
            size="small"
            @click="viewItemDetail(item)"
            style="margin-right: 10px;">
            查看详情
          </el-button>
          <el-button
            :type="canPurchase(item) ? 'success' : 'info'"
            size="small"
            @click="purchaseItem(item)"
            :disabled="!canPurchase(item)">
            {{ getPurchaseButtonText(item) }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 推荐原因说明 -->
    <div class="recommendation-reasons">
      <el-collapse>
        <el-collapse-item title="为什么推荐这些商品？" name="reasons">
          <div class="reason-item">
            <i class="el-icon-star-on" style="color: #E6A23C;"></i>
            <span>基于您的信用分等级，为您筛选了优质商品</span>
          </div>
          <div class="reason-item">
            <i class="el-icon-shopping-bag-2" style="color: #409EFF;"></i>
            <span>根据您的浏览和购买历史，推荐相关商品</span>
          </div>
          <div class="reason-item">
            <i class="el-icon-thumb" style="color: #67C23A;"></i>
            <span>同等信用分用户的热门选择</span>
          </div>
          <div class="reason-item">
            <i class="el-icon-discount" style="color: #F56C6C;"></i>
            <span>信用分专享优惠，享受更低价格</span>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script>
import { getGoodsRecommend, buyGoods } from '@/api/credit/businessService'

export default {
  name: "GoodsRecommendation",
  props: {
    userScore: {
      type: Number,
      default: 750
    }
  },
  data() {
    return {
      activeTag: 'hot',
      recommendationTags: [
        { id: 'hot', name: '热门推荐' },
        { id: 'credit', name: '信用专享' },
        { id: 'electronics', name: '数码电子' },
        { id: 'lifestyle', name: '生活用品' },
        { id: 'sports', name: '运动健身' }
      ],
      recommendations: [],
      loading: false
    };
  },
  computed: {
    /** 过滤后的推荐商品 */
    filteredRecommendations() {
      if (this.activeTag === 'hot') {
        return this.recommendations.filter(item => item.tags && item.tags.includes('热门推荐'));
      } else if (this.activeTag === 'credit') {
        return this.recommendations.filter(item => item.tags && item.tags.includes('信用专享'));
      } else if (this.activeTag === 'electronics') {
        return this.recommendations.filter(item => item.goodsCategory === '数码电子');
      } else if (this.activeTag === 'lifestyle') {
        return this.recommendations.filter(item => item.goodsCategory === '生活用品');
      } else if (this.activeTag === 'sports') {
        return this.recommendations.filter(item => item.goodsCategory === '运动健身');
      }
      return this.recommendations;
    }
  },
  created() {
    this.getRecommendations();
  },
  methods: {
    /** 获取商品推荐 */
    getRecommendations() {
      this.loading = true;
      getGoodsRecommend().then(response => {
        if (response.code === 200) {
          this.recommendations = response.data || [];
          // 为每个商品添加默认标签
          this.recommendations.forEach(item => {
            if (!item.tags) {
              item.tags = ['信用专享'];
            }
            // 确保所有商品都有热门推荐标签
            if (!item.tags.includes('热门推荐')) {
              item.tags.push('热门推荐');
            }
          });
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 切换推荐标签 */
    changeRecommendationTag(tagId) {
      this.activeTag = tagId;
    },
    /** 查看商品详情 */
    viewItemDetail(item) {
      this.$alert(`
        <div style="text-align: left;">
          <h3>${item.goodsName}</h3>
          <p><strong>分类：</strong>${item.goodsCategory}</p>
          <p><strong>价格：</strong>¥${item.goodsPrice}</p>
          <p><strong>推荐信用分：</strong>${item.recommendScore}分</p>
          <p><strong>库存：</strong>${item.stockQuantity || 0}件</p>
          <p><strong>推荐原因：</strong>${item.reason || '基于您的信用分推荐'}</p>
          <p><strong>描述：</strong>${item.goodsDesc || '暂无详细描述'}</p>
        </div>
      `, '商品详情', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        customClass: 'goods-detail-dialog'
      });
    },
    /** 购买商品 */
    purchaseItem(item) {
      console.log('当前用户信用分:', this.userScore);
      console.log('商品所需信用分:', item.recommendScore);
      console.log('是否可以购买:', this.canPurchase(item));
      if (!this.canPurchase(item)) {
        this.$message.warning(`您的信用分不足，需要${item.recommendScore}分才能享受此优惠`);
        return;
      }
      this.$confirm(`确认购买"${item.goodsName}"？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const buyData = {
          goodsId: item.goodsId,
          quantity: 1,
          paymentMethod: "installment"
        };
        buyGoods(buyData).then(response => {
          if (response.code === 200) {
            this.$message.success(response.data.message || "购买成功，享受信用分期服务");
            this.getRecommendations(); // 刷新推荐列表
          } else {
            this.$message.error(response.msg || "购买失败");
          }
        }).catch(() => {
          this.$message.error("购买失败，请稍后重试");
        });
      });
    },
    // /** 检查是否可以购买 */
    // canPurchase(item) {
    //   return this.userScore >= item.recommendScore;
    // },
    // /** 获取购买按钮文本 */
    // getPurchaseButtonText(item) {
    //   if (this.canPurchase(item)) {
    //     return '立即购买';
    //   } else {
    //     return `需要${item.recommendScore}分`;
    //   }
    // },
    /** 检查是否可以购买 */
    canPurchase(item) {
      // 确保userScore和recommendScore都是数字
      const userScore = Number(this.userScore) || 0;
      const recommendScore = Number(item.recommendScore) || 0;
      return userScore >= recommendScore;
    },

    /** 获取购买按钮文本 */
    getPurchaseButtonText(item) {
      // 根据canPurchase结果返回不同的文本
      return this.canPurchase(item) ? '立即购买' : `需要${item.recommendScore}分`;
    },
    /** 获取徽章类型 */
    getBadgeType(badge) {
      const typeMap = {
        '信用专享': 'success',
        '热门推荐': 'danger',
        '分期免息': 'warning',
        '限时优惠': 'info',
        '旗舰体验': 'warning',
        '降噪': 'info',
        '信用优惠': 'success',
        '运动': 'primary',
        '生活': 'success'
      };
      return typeMap[badge] || 'info';
    },
    /** 获取商品图片 */
    getItemImage(item) {
      // 如果有图片地址，使用后端提供的图片
      if (item.goodsImages) {
        try {
          const images = JSON.parse(item.goodsImages);
          if (images && images.length > 0) {
            return this.getImageUrl(images[0]);
          }
        } catch (e) {
          console.warn('解析商品图片失败:', e);
        }
      }
      // 根据分类返回默认图片
      const imageMap = {
        '数码电子': '',
        '运动健身': '',
        '生活用品': ''
      };
      return imageMap[item.goodsCategory] || '';
    },
    /** 处理图片加载错误 */
    handleImageError(event) {
      event.target.src = '';
    },
    /** 获取图片完整URL */
    getImageUrl(imagePath) {
      if (!imagePath) return '';
      if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
        return imagePath;
      }
      // 如果是相对路径，添加基础URL
      return process.env.VUE_APP_BASE_API + imagePath;
    }
  }
};
</script>

<style scoped>
.recommendation-header {
  text-align: center;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px;
  margin-bottom: 20px;
}

.recommendation-header h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
}

.recommendation-header p {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.recommendation-tags {
  margin-bottom: 20px;
  text-align: center;
}

.recommendation-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.recommendation-card {
  position: relative;
  border: 1px solid #EBEEF5;
  border-radius: 12px;
  padding: 15px;
  transition: all 0.3s;
}

.recommendation-card:hover {
  border-color: #409EFF;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.item-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 1;
}

.item-image {
  position: relative;
  width: 100%;
  height: 150px;
  margin-bottom: 15px;
  border-radius: 8px;
  overflow: hidden;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-score-badge {
  position: absolute;
  bottom: 5px;
  left: 5px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.item-info {
  margin-bottom: 15px;
}

.item-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.item-description {
  font-size: 12px;
  color: #606266;
  margin-bottom: 10px;
  line-height: 1.4;
}

.item-features {
  margin-bottom: 10px;
}

.item-price {
  margin-bottom: 10px;
}

.current-price {
  font-size: 18px;
  font-weight: bold;
  color: #E6A23C;
  margin-right: 8px;
}

.original-price {
  font-size: 12px;
  color: #C0C4CC;
  text-decoration: line-through;
  margin-right: 8px;
}

.discount {
  font-size: 12px;
  color: #F56C6C;
  font-weight: bold;
}

.item-rating {
  display: flex;
  align-items: center;
}

.sales-count {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
}

.item-actions {
  text-align: center;
}

.recommendation-reasons {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
}

.reason-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.reason-item i {
  margin-right: 10px;
  font-size: 16px;
}

.reason-item:last-child {
  margin-bottom: 0;
}
</style>
